using Admin2025.Application.Events;
using Admin2025.Domain.Entities;
using MediatR;

namespace Admin2025.Application.Extensions;

/// <summary>
/// 领域事件扩展方法
/// </summary>
public static class DomainEventExtensions
{
    private static readonly IDomainEventNotificationFactory _notificationFactory = new ReflectionDomainEventNotificationFactory();

    /// <summary>
    /// 发布实体的所有领域事件
    /// </summary>
    /// <param name="mediator">MediatR实例</param>
    /// <param name="entity">实体</param>
    /// <param name="cancellationToken">取消令牌</param>
    public static async Task PublishDomainEventsAsync(this IMediator mediator, EntityBase entity, CancellationToken cancellationToken = default)
    {
        if (entity.DomainEvents.Any())
        {
            var events = entity.DomainEvents.ToList();
            entity.ClearDomainEvents();

            // 使用工厂自动创建对应的通知类型，无需手动维护映射关系
            foreach (var domainEvent in events)
            {
                var notification = _notificationFactory.CreateNotification(domainEvent);
                if (notification != null)
                {
                    await mediator.Publish(notification, cancellationToken);
                }
            }
        }
    }

    /// <summary>
    /// 批量发布多个实体的领域事件
    /// </summary>
    /// <param name="mediator">MediatR实例</param>
    /// <param name="entities">实体集合</param>
    /// <param name="cancellationToken">取消令牌</param>
    public static async Task PublishDomainEventsAsync(this IMediator mediator, IEnumerable<EntityBase> entities, CancellationToken cancellationToken = default)
    {
        foreach (var entity in entities)
        {
            await mediator.PublishDomainEventsAsync(entity, cancellationToken);
        }
    }
}
